package com.ronghuanet.user.controller;

import com.ronghuanet.basic.util.AjaxResult;
import com.ronghuanet.user.dto.SmsCodeDto;
import com.ronghuanet.user.service.IVerifyCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private IVerifyCodeService verifyCodeService;
    @GetMapping("/img/{key}")
    public AjaxResult getImgeCode(@PathVariable("key") String key){
        try {
            String base64ImageCode = verifyCodeService.getImageCode(key);
            return AjaxResult.me().setResult(base64ImageCode);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取图片验证码失败!"+e.getMessage());
        }
    }

    //发送注册短信验证码
    @PostMapping("/sms/register")
    public AjaxResult sendSmsCodeRegister(@RequestBody SmsCodeDto smsCodeDto){
        try {
            return verifyCodeService.sendSmsCodeRegister(smsCodeDto);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("发送注册短信验证码失败!"+e.getMessage());
        }
    }
    /*  非前后端分离的方案
    @GetMapping("/img")
    public void imgeCode(HttpSession session, HttpServletResponse response){

        //产生验证码
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);

        //存放session
        session.setAttribute("verifyCode",verifyCode);

        //把验证码最为图片响应给客户端
        try {
            ServletOutputStream os = response.getOutputStream();
            VerifyCodeUtils.outputImage(200,40,os,verifyCode);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}
